<?php

namespace catchAdmin\api\controller;

use baidu\Tts;
use catchAdmin\externalGoods\model\GoodsAttribute;
use catchAdmin\externalGoods\model\GoodsRule as externalGoodsRuleModel;
use catchAdmin\externalGoods\model\News as newsModel;
use catchAdmin\externalGoods\model\TenantGoods;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use QL\QueryList;
use think\Exception;
use think\facade\Db;
use think\facade\Request;
use catchAdmin\externalGoods\model\search\NewsSearch;
use think\Facade\Log;
use think\facade\Request as ThinkRequest;

/*
 * 新闻
 * */
class News  extends Index
{
    use NewsSearch;

    public function __construct(newsModel $newsModel)
    {
        $this->newsModel = $newsModel;
    }

    public function abced(Request $request){
        $dta = $request::param();
        return CatchResponse::success(['data'=>$dta,'abc'=>json_decode($dta['biz_content'],true)['parent_cat_id']]);
    }

    //列表
    public function index(Request $request)
    {
//        file_put_contents('./xie',time() . PHP_EOL,FILE_APPEND);
//        sleep(6);
//        return CatchResponse::success([111]);

        $where = [];
//        $where[] = ['is_rec','=',1];
        $where[] = ['publish','=',1];
        $listRows = ['list_rows'=>$request::get('limit',20)];

        $result =  $this->newsModel
            ->field('id,source,search_name,title,path,cover_url,post_time,voice_count,_ext_field_1,is_rec,is_rec2,tags,publish_title')
            ->catchSearch()
            ->where($where)
            ->order('post_time', 'desc')
            ->paginate($listRows)
            ->each(function($item){
                //不为空
                if(!empty($item->tags)){
                    $item->tags = explode(',',$item->tags);
                }else{
                    $item->tags = [];
                }
                

                //判断发布标题是否不为空
                if(!empty($item->publish_title)){
                    $item->title = $item->publish_title;
                }

                unset($item->publish_title);
            });

        return CatchResponse::paginate($result);
    }

    //列表
    public function index1(Request $request)
    {
//        file_put_contents('./xie',time() . PHP_EOL,FILE_APPEND);
//        sleep(5);
//        return CatchResponse::success([mt_rand(0,1000)]);
        $where = [];
//        $where[] = ['is_rec','=',1];
        $listRows = ['list_rows'=>$request::get('limit',20)];

        $result =  $this->newsModel
            ->field('id,source,search_name,title,path,cover_url,post_time,voice_count,_ext_field_1,is_rec,is_rec2')
            ->catchSearch()
            ->where($where)
            ->order('post_time', 'desc')
            ->paginate($listRows);

        return CatchResponse::paginate($result);
    }

    //详情
    public function detail($id,CatchAuth $auth)
    {
        $field = ['*'];
        $result = $this->newsModel->findBy($id,$field);
        if($result){
            if(!$result['voice_task_id']) {
                //创建任务 暂时用不到，先注释去掉了
                //$this->makeVoice($id);
            }
        }

        return CatchResponse::success($result);
    }

    //同源最近两篇文章
    public function latest(){
        $field = ['*'];
        $search_name = $this->newsModel->order('post_time','desc')->value('search_name');
        $result = $this->newsModel->field($field)->where('search_name',$search_name)
            ->order('post_time','desc')->limit(2)->select()->toArray();

        return CatchResponse::success($result);
    }

    //语音任务
    public function makeVoice($id){
        $result = $this->newsModel->findBy($id,['voice_url','content_html','source']);
        $textArr = [];
        $ql = QueryList::html($result['content_html']);
        $ql->find('title')->remove();
        $ql->find('style')->remove();

        $ql->find('*')->each(function($item) use (&$textArr){
            if(count($item->children()->elements) == 0){
                $t = trim($item->text());
                $t = mb_ereg_replace('^(　| )+','', $t);//去除空格（全角+半角）
                $textArr[] = $t;
            }
        });

        $textArr = array_values(array_filter($textArr));

        $tts = new Tts;
        $create_result = json_decode($tts->create($textArr),true);

        if(array_key_exists('error_code',$create_result)){//失败
            //Log::error('语音任务创建失败' . $create_result['error_msg']);
            //dd($create_result['error_msg']);die();
            //throw new Exception('语音任务创建失败' . $create_result['error_msg']);
        }else{
            $result->voice_task_id = $create_result['task_id'];
            $result->save();
        }
    }

    //语音地址、接口
    public function voice($id){
        $result = $this->newsModel->findBy($id,['voice_url','content_html','source','voice_task_id','voice_count']);
        if(!$result) return CatchResponse::fail('文章不存在');
        if(!empty($result['voice_url'])){
            $result->voice_count +=1;
            $result->save();
            return CatchResponse::success(['voice_url'=>$result['voice_url']]);
        }
//        $content = str_replace([" ","\t","\n","\r"], "", $html_string);

        $tts = new Tts;
        try {
            if(!$result['voice_task_id']){//没创建的话，一般不会存在
                $this->makeVoice($id);
                throw new Exception('语音转换中、请几秒后尝试');
            }
            $query_result = json_decode($tts->query($result['voice_task_id']),true);

            //dd($query_result);die();
            if(array_key_exists('error_code',$query_result)){//失败
                //Log::error('语音任务查询失败' . $query_result['error_msg']);
                throw new Exception('语音任务查询失败' . $query_result['error_msg']);
            }

            $info = $query_result['tasks_info'][0];
            if($info['task_status'] != 'Success'){
                throw new Exception('语音转换中、请几秒后尝试');
            }

            $result->voice_url = $query_result['tasks_info'][0]['task_result']['speech_url'];
            $result->save();
        }catch (\Exception $exception){
            return CatchResponse::fail('系统错误 ' . $exception->getMessage());
        }

        $result->voice_count +=1;
        $result->save();
        return CatchResponse::success(['voice_url'=>$result->voice_url]);
    }

    //海关商品 临时接口详情
    public function tempGoods($goods_spu)
    {
        //$tenantGoodsModel = new TenantGoods();
        $request = (new ThinkRequest);
        //$goods_spu =  $request::post('goods_spu');

        $goods = (new \catchAdmin\externalGoods\model\Goods())
            ->field('goods_spu,
            goods_name,
            goods_subtitle,
            goods_keywords,
            goods_img,
            goods_slideshow_img,
            barcode,
            brand_id,
            brand_name,
            origin_id,
            origin_name,
            trade_type_id,
            trade_type_name,
            unit_id,
            unit_name,
            is_sale,
            category_id,
            sync_category_id_path as category_id_path,
            sync_category_name as category_name,
            description,
            price,
            stock')->where('goods_spu',$goods_spu)->find();
        if(!$goods){
            return [ 'code'=>Code::FAILED , 'msg'=> '商品不存在' ];
        }

        $goods['goods_pic'] = $goods['goods_img'];//主图
        $goods_slideshow_img = array_merge([$goods['goods_pic']], json_decode($goods['goods_slideshow_img'],true));
        $goods['goods_slideshow_img'] =$goods_slideshow_img;//轮播图包含主图

        //
        $goods['attr'] = (new GoodsAttribute)
            ->field('attribute_id,name,attribute_name')
            ->where('goods_id',$goods['syst_goods_id'])->select()->toArray();
        $goods['rule'] = (new externalGoodsRuleModel)
            ->field('goods_sku,spec_sku,sku_name,sku_attribute_id,sku_attribute_name,sku_price,sku_stock')
            ->where('goods_id',$goods['syst_goods_id'])->select()->toArray();

        return ['code'=>Code::SUCCESS, 'msg' => '商品详情获取成功', 'data' => $goods];
        //return CatchResponse::paginate($tenantGoodsModel->getList($this->merchantInfo['tenant_id']));
    }

    //海关商品 临时接口详情
    public function tempGoods2($goods_spu)
    {
        //$tenantGoodsModel = new TenantGoods();
        $request = (new ThinkRequest);
        //$goods_spu =  $request::post('goods_spu');

        $goods = Db::connect('mysql_df_remote')->table('db_product')
            ->where([
                'prod'=>$goods_spu,
//                'ifshow'=>1
            ])->order('pid desc')->find();

        if(!$goods){
            return [ 'code'=>Code::FAILED , 'msg'=> '商品不存在' ];
        }

        $photo = $goods['photo'];
        $all_photo = explode(',',$photo);

        $goods['goods_pic'] = $all_photo[0];//主图
        $goods['goods_slideshow_img'] =$all_photo;//轮播图包含主图
        $goods['trade_type_name'] = '保税贸易';
        $goods['goods_spu'] = $goods['prod'];
        $goods['origin_name'] = $goods['product_area'];
        $goods['unit_name'] = $goods['Unit2'];
        $goods['brand_name'] = $goods['bra'];
        $goods['description'] = $goods['detail_img'];

//        //
//        $goods['attr'] = (new GoodsAttribute)
//            ->field('attribute_id,name,attribute_name')
//            ->where('goods_id',$goods['syst_goods_id'])->select()->toArray();
//        $goods['rule'] = (new externalGoodsRuleModel)
//            ->field('goods_sku,spec_sku,sku_name,sku_attribute_id,sku_attribute_name,sku_price,sku_stock')
//            ->where('goods_id',$goods['syst_goods_id'])->select()->toArray();

        return ['code'=>Code::SUCCESS, 'msg' => '商品详情获取成功', 'data' => $goods];
        //return CatchResponse::paginate($tenantGoodsModel->getList($this->merchantInfo['tenant_id']));
    }
}